<?php if (!defined('BASEPATH')) exit ('No direct script access allowed');
//where belum dikerjakan
class Server_processing{
	var $server;
	function __construct()
	{
		$CI =& get_instance();
	}
	function server_data($param,$init){
	/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
	 * Easy set variables
	 */
	
	/* Array of database columns which should be read and sent back to DataTables. Use a space where
	 * you want to insert a non-database field (for example a counter or static image)
	 */
		
	/* DB table to use */
	$sTable = $init['table_name'];
	// jika join di inisialisasi
	if($init['join'] != NULL){
		$sJoin = "";
		for($i=0;$i<count($init['join']);$i++){
			$sJoin .= " INNER JOIN ".$init['join'][$i]." ON ".$init['on'][$i];  
			}
		}
	else
	{
		$sJoin = "";
	}
	// jika select di inisialisasi
	if($init['select'] != NULL){
		$aColumns = $init['select'];
		for($i=0; $i<count($aColumns);$i++)
		{$aColumns[$i] = str_replace(".", "`.`", $aColumns[$i]);}
	}
	else{
		$query = "SELECT * FROM $sTable $sJoin";
		$field = mysql_query($query);
		$num_field = mysql_num_fields($field);
		$aColumns = array();
		for ($i = 0; $i < $num_field; ++$i) {
			$aColumns[$i] = mysql_field_table($field, $i).".".mysql_field_name($field, $i);
			$aColumns[$i] = str_replace(".", "`.`", $aColumns[$i]);
		}
	}

	/* Indexed column (used for fast and accurate table cardinality) */
	$sIndexColumn = "$aColumns[0]";
	
	/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
	 * If you just want to use the basic configuration for DataTables with PHP server-side, there is
	 * no need to edit below this line
	 */
	
	/* 
	 * Local functions
	 */
	function fatal_error ( $sErrorMessage = '' )
	{
		header( $_SERVER['SERVER_PROTOCOL'] .' 500 Internal Server Error' );
		die( $sErrorMessage );
	}

	

	/* 
	 * Paging
	 */
	$sLimit = "";
	if ( isset( $param['iDisplayStart'] ) && $param['iDisplayLength'] != '-1' )
	{
		$sLimit = "LIMIT ".intval( $param['iDisplayStart'] ).", ".
			intval( $param['iDisplayLength'] );
	}
	
	
	/*
	 * Ordering
	 */
	$sOrder = "";
	if ( isset( $param['iSortCol_0'] ) )
	{
		$sOrder = "ORDER BY  ";
		for ( $i=0 ; $i<intval( $param['iSortingCols'] ) ; $i++ )
		{
			if ( $param[ 'bSortable_'.intval($param['iSortCol_'.$i]) ] == "true" )
			{
				// ini di edit karena field 1 bukan dari database
				$sOrder .= "`".$aColumns[ intval( $param['iSortCol_'.$i] ) ]."` ".
					($param['sSortDir_'.$i]==='asc' ? 'asc' : 'desc') .", ";
			}
		}
		
		$sOrder = substr_replace( $sOrder, "", -2 );
		if ( $sOrder == "ORDER BY" )
		{
			$sOrder = "ORDER BY ".$sIndexColumn;
		}
	}
	
	/* 
	 * Filtering
	 * NOTE this does not match the built-in DataTables filtering which does it
	 * word by word on any field. It's possible to do here, but concerned about efficiency
	 * on very large tables, and MySQL's regex functionality is very limited
	 */
	$sWhere = "";
	if ( isset($param['sSearch']) && $param['sSearch'] != "" )
	{
		$sWhere = "WHERE (";
		for ( $i=0 ; $i<count($aColumns) ; $i++ )
		{
			if ( isset($param['bSearchable_'.$i]) && $param['bSearchable_'.$i] == "true" )
			{
				$sWhere .= "`".$aColumns[$i]."` LIKE '%".mysql_real_escape_string( $param['sSearch'] )."%' OR ";
			}
		}
		$sWhere = substr_replace( $sWhere, "", -3 );
		$sWhere .= ')';
	}
	
	/* Individual column filtering */
	for ( $i=0 ; $i<count($aColumns) ; $i++ )
	{
		if ( isset($param['bSearchable_'.$i]) && $param['bSearchable_'.$i] == "true" && $param['sSearch_'.$i] != '' )
		{
			if ( $sWhere == "" )
			{
				$sWhere = "WHERE ";
			}
			else
			{
				$sWhere .= " AND ";
			}
			$sWhere .= "`".$aColumns[$i]."` LIKE '%".mysql_real_escape_string($param['sSearch_'.$i])."%' ";
		}
	}
	
	
	/*
	 * SQL queries
	 * Get data to display
	 */
	$sQuery = "
		SELECT SQL_CALC_FOUND_ROWS `".str_replace(" , ", " ", implode("`, `", $aColumns))."`
		FROM   $sTable
		$sJoin 
		$sWhere
		$sOrder
		$sLimit
		";
//	echo $sQuery;die();
	$rResult = mysql_query( $sQuery ) or fatal_error( 'MySQL Error: ' . mysql_errno() );	
	/* Data set length after filtering */
	$sQuery = "
		SELECT FOUND_ROWS()
	";
	$rResultFilterTotal = mysql_query( $sQuery ) or fatal_error( 'MySQL Error: ' . mysql_errno() );
	$aResultFilterTotal = mysql_fetch_array($rResultFilterTotal);
	$iFilteredTotal = $aResultFilterTotal[0];
	
	/* Total data set length */
	$sQuery = "
		SELECT COUNT(`".$sIndexColumn."`)
		FROM   $sTable
	";
	$rResultTotal = mysql_query( $sQuery ) or fatal_error( 'MySQL Error: ' . mysql_errno() );
	$aResultTotal = mysql_fetch_array($rResultTotal);
	$iTotal = $aResultTotal[0];
	
	
	/*
	 * Output
	 */
	$output = array(
		"sEcho" => intval($param['sEcho']),
		"iTotalRecords" => $iTotal,
		"iTotalDisplayRecords" => $iFilteredTotal,
		"aaData" => array()
	);


	
	while ( $aRow = mysql_fetch_array( $rResult ) )
	{
		$row = array();
		// Add the row ID and class to the object
		$row['DT_RowId'] = 'row_'.$aRow[0];
		//$row['DT_RowClass'] = 'grade'.$aRow['grade'];
		
		for ( $i=0 ; $i<count($aColumns) ; $i++ )
		{
				/* General output */
				$row[] = $aRow[ $i ];
		}
		$row[count($aColumns)] = 
anchor($init['uri'].'/update/'.$row[0],'<i class="icon-pencil" style="font-size:18px;"></i>').'&nbsp;&nbsp;&nbsp;&nbsp;'.anchor($init['uri'].'/delete/'.$row[0],'<i class="icon-trash" style="font-size:18px;"></i>',array('onclick'=>"return confirm('Apakah anda yakin ingin menghapus data ini?')"))		
		;
		$output['aaData'][] = $row;
	}
	
	echo json_encode( $output );
	}
}